/**
* @author als31@aber.ac.uk
*/


#include "viewpanel.h"

#include <sstream>


int curInd = 0;

ViewPanel::ViewPanel(QWidget *parent, View viewType) :
    QGLWidget(parent), _viewType(viewType)
{
    _currentImage = new QImage(5,5,QImage::Format_RGB32);
    this->setMaximumSize(640,480);
}


void ViewPanel::updateImage(const void *data, int height, int width, StreamSource source)
{
    convertToQImage(data,height,width,source);
    repaint();
}

void ViewPanel::convertToQImage(const void *data, int height, int width, StreamSource source){

    if(_currentImage != NULL)
        delete _currentImage;

    _currentImage = new QImage(width, height,QImage::Format_RGB32);

    for(int i = 0 ; i < height ; i++){
        for(int j = 0 ; j < width ; j++){
            QColor c;
            if( source == DEPTH_SENSOR ){
                openni::DepthPixel pix = ((openni::DepthPixel*)data)[i*width + j];
                pix = ( pix * 255 ) / 10000;
                c.setRgb(pix,pix,pix);
            }else if ( source == COLOR_SENSOR ){
                openni::RGB888Pixel pix = ((openni::RGB888Pixel*)data)[i*width +j];
                c.setRgb(pix.r,pix.g,pix.b);
            }else{
                std::cerr << "Unexpected Source Sensor!" << std::endl;
            }

            _currentImage->setPixel(j,i,c.rgb());
        }
    }

    //    std::stringstream ss;
    //    ss << "imgs/img_"<< curInd++ << ".png";
    //    img.save(QString(ss.str().c_str()));
}

void ViewPanel::paintEvent(QPaintEvent *pe){
    QPainter painter(this);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, 1);
    painter.drawImage(this->rect(),* _currentImage);
}

void ViewPanel::mousePressEvent(QMouseEvent *){
    emit selected(this->_viewType);
}
